/*
 * @lc app=leetcode.cn id=1370 lang=javascript
 *
 * [1370] 上升下降字符串
 */

// @lc code=start
var getMap = function (word) {
  const map = {};
  word.split('').forEach(ch => {
    map[ch] = map[ch] ? map[ch] + 1 : 1;
  });
  return map;
}
/**
 * @param {string} s
 * @return {string}
 */
var sortString = function (s) {
  const map = Object
    .entries(getMap(s))
    .sort(([a], [b]) => {
      if (a < b) return -1;
      if (a > b) return 1;
      return 0;
    });
  let len = s.length;
  let res = '';
  while (len) {
    for (let i = 0; i < map.length; i++) {
      if (map[i][1] > 0) {
        res += map[i][0];
        map[i][1]--;
        len--;
      }
    }
    for (let i = map.length - 1; i >= 0; i--) {
      if (map[i][1] > 0) {
        res += map[i][0];
        map[i][1]--;
        len--;
      }
    }
  }
  return res;
};
// @lc code=end
